<template>
  <pre ref="scripts" @click="onCopyScript">{{ ddl }}</pre>
</template>
<script setup>
  import { useRoute } from 'vue-router';
  import { ref, inject, watch, onMounted } from 'vue';
  import { Toast } from 'vant';

  const $route = useRoute();

  const $http = inject('$http');
  const $copyText = inject('$copyText');

  const props = defineProps({
    table: String
  });

  const ddl = ref('');

  watch(
    () => props.table,
    () => getTableDDL()
  );

  function getTableDDL() {
    let dbIndex = $route.params.dbIndex;
    let schema = $route.params.schema;
    let dbType = $route.query.dbtype;
    let tableName = props.table;

    if (dbIndex && schema && tableName) {
      $http.get(`/api/db/${dbIndex}/${schema}/${tableName}/ddl`).then(res => (ddl.value = res.data['Create Table']));
    }
  }

  function onCopyScript() {
    $copyText(ddl.value).then(() => {
      Toast.success('脚本已复制！');
    });
  }

  onMounted(() => {
    getTableDDL();
  });
</script>
<style lang="less" scoped>
  pre {
    margin: 0;
    background: #fff;
    border-radius: 5px;
    overflow: auto;
    padding: 5px 10px;
    height: 100%;
  }
</style>
